<template>
    <div class="dhzn_goodsdetails">
        <div class="d_d-content" v-if="pageingstate !== 2">
            <!-- 查询 -->
            <div class="d_d-c-query mb10">
                <el-form :model="selectqurey" label-width="72px" ref="selectqurey" :rules="rules" inline size='mini' class="d_dcq-form">
                    <el-form-item label="查询类型" prop='type'>
                        <el-select v-model="selectqurey.type" clearable>
                            <el-option label="满减商品详情" value="0"></el-option>
                            <el-option label="包邮商品详情" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="requestquery('selectqurey'),currentPage=1,pageingstate=1">查询</el-button>
                        <el-button type="danger" @click="abolish('selectqurey'),currentPage=1,goodsActivity(),pageingstate=0">取消</el-button>
                    </el-form-item>
                </el-form>
                <span class="bc4a wh br5 f14 p5 cup" @click="pageingstate = 2">添加商品详情</span>
            </div>

            <!-- 数据列表 -->
            <div class="d_d-c-list f14">
                <!-- 数据表 -->
                <table class="d_dcl-tabel tc">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图片</th>
                            <th>商品</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in basiclist" :key="key">
                            <td>{{item.id}}</td>
                            <td class="f0 pt5 pb5">
                                <!-- <img :src="item.imageurl" alt=""> -->
                                <el-popover placement="top" popper-class="d_gld-t-popover" trigger="click" v-model="item.visible">
                                    <img :src="item.imageurl">
                                    <img slot="reference" :src="item.imageurl">
                                </el-popover>
                            </td>
                            <td>{{item.goodsid | filname}}</td>
                            <td>
                                <button type="button" class="wh bc4a br5 pt5 pb5" @click="dialogstate=true,activityupdate.imageurl=item.imageurl,activityupdate.id=item.id,activityupdate.key=key"><i class="el-icon-edit-outline"></i>修改</button>
                                <button type="button" class="wh bcfd br5 pt5 pb5" @click="requestdelete(item.id,key)">删除<i class="el-icon-delete"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div class="d_rj-block mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
            <!-- 弹出层 -->
            <el-dialog title="修改商品详情信息" :visible.sync="dialogstate" width="400px" center>
                <div class="d_dc-dialog">
                    <span>修改上传图片</span>
                    <el-upload
                        action="/api/file/upload"
                        :headers="headers" 
                        name="files"
                        ref="upload"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-success="handsuccess">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </div>
                <span slot="footer">
                    <el-button @click="dialogstate = false">取 消</el-button>
                    <el-button type="primary" @click="requestupdate">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <!-- 添加模块 -->
        <div class="d_d-add" v-else>
            <div class="d_d-a-title bb1 mb10"><span class="wh bc4a dib br5 p5 mb10 f14 cup" @click="pageingstate = 0">返回列表</span></div>
            <div class="d_d-a-content">
                <el-form label-width="80px" ref="activityadd" :rules="rules" class="d_dac-form">

                    <el-form-item label="详情图片">
                        <el-upload
                            action="/api/file/upload"
                            :headers="headers" 
                            name="files"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-success="handsuccess">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="requestadd('activityadd'),pageingstate = 0">提交</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
let axios = require('axios')
let that
export default {
    components: {},
    data() {
        return {
            id: '',                             //路由传值
            token: '',                          //身份验证
            pageingstate: 0,                    //页面切换分页运行函数的状态管理
            headers:'',
            goodsname: '',
            basiclist: [],
            // 查询条件绑定对象
            selectqurey: {
                type:''
            },
            // 修改字段绑定对象
            activityupdate:{
                id: '',
                imageurl: '',
                key:''
            },
            // 添加字段绑定对象
            activityadd:{
                imageurl: '',
            },
            // 输入验证
            rules:{
                type:[
                    {required:true,message:'请选择商品详情类型',trigger:'change'}
                ],
                full:[
                    {required:true,message:'请输入触发条件',trigger:'change'}
                ],
                reduce:[
                    {required:true,message:'请输入商品详情力度',trigger:'change'}
                ],
            },
            imageurl: '',
            dialogImageUrl: '',
            dialogVisible: false,
            dialogstate: false,                 //弹出层状态
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
        };
    },
    filters:{
        filtertype(type){
            if(type === 0){
                type = '满减'
            }else{
                type = '包邮'
            }
            return type
        },
        // 商品名称
        filname(id){
            that.goodsname.forEach((item)=>{
               item.id === id ? id = item.name : ''
            })
            return id
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            let that = this;
            that.pagesize = val;
            if(that.pageingstate === 0){
                that.goodsActivity()
            }else{
                that.requestquery('selectqurey')
            }
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val;
            if(that.pageingstate === 0){
                that.goodsActivity()
            }else{
                that.requestquery('selectqurey')
            }
        },

        // 添加商品详情
        requestadd(add){
            let that = this;
            if(that.imageurl !== ""){
                let data = {goodsid:that.id,imageurl:that.imageurl};
                let updata = JSON.stringify(data);
                axios({
                    method: 'post',
                    url: '/api/goodsDetails/add',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=>{ 
                    console.log(resp)
                    data.id = resp.data.data;
                    data.goodsid = that.id
                    that.basiclist.length < that.pagesize ? that.basiclist.push(data) : '';
                    that.total += 1;
                    that.imageurl = '';
                    for(var u in that.activityadd) that.activityadd[u] = "";
                }).catch( err=> {console.log(err)})
            }else{this.$message("请在图片上传成功后提交")}
        },

        // 删除商品详情
        requestdelete(id,key){
            let that = this;
            let updata = JSON.stringify({id: id});
            that.$confirm('此操作将永久删除该文件, 是否继续?', '提示',{
                confirmButtonText:'确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/goodsDetails/delete',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(resp.data.data === '删除成功！'){
                        that.basiclist.splice(key,1);
                        that.total--
                    }
                }).catch( err=> {console.log(err)})

                this.$message({
                    type: 'success',
                    message: '删除成功'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 修改商品详情
        requestupdate(){
            let that = this;
            if(that.imageurl !== ""){
                that.dialogstate = false
                this.$refs.upload.clearFiles()
                let data = {};
                for(var o in that.activityupdate) o!=='key' && that.activityupdate[o] !== null ? data[o] = that.activityupdate[o] : '';
                let updata = JSON.stringify(data)
                axios({
                    method: 'post',
                    url: '/api/goodsDetails/update',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    let key = that.activityupdate.key
                    for(var u in data) that.basiclist[key][u] === data[u] ? '' : that.basiclist[key][u] = data[u];
                }).catch( err=> {console.log(err)})
            }else{this.$message("请在图片上传成功后提交")}
        },

        // 商品详情
        goodsActivity(){
            let that = this;
            let data = {current: that.currentPage,size:that.pagesize,goodsid:that.id};
            let updata = JSON.stringify(data);
            axios({    
                method: 'post',
                url: '/api/goodsDetails/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> { 
                // console.log('商品详情',resp)
                that.basiclist = resp.data.data;
                that.total = resp.data.code;
            }).catch( err=>{console.log(err)})
        },

        // 查找
        requestquery(query){
            let that = this;
            that.$refs[query].validate((valid)=>{
                if(valid){
                    let data = {current:that.currentPage,size:that.pagesize,goodsid: that.id,type:that.selectqurey.type};
                    let updata = JSON.stringify(data)
                    console.log(data,updata)
                    axios({    
                        method: 'post',
                        url: '/api/goodsDetails/list',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> { 
                        console.log('商品详情',resp)
                        that.basiclist = resp.data.data;
                        that.total = resp.data.code;
                    }).catch( err=>{console.log(err)})
                }else{return}
            })
        },
        // 取消查询
        abolish(query){
            this.$refs[query].resetFields()
        },

        // 上传图片
        handsuccess(response,file,fileList){
            console.log(response)
            that.imageurl = 'http://dzy.dpyun.site/upload/images/' + response.data[0]
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        
        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
                sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.headers = {'authorization': `Bearer ${resp.data.data}`}
                that.goodsActivity()
			}).catch( err=> {})
        }
    },
    created() {},
    mounted() {
        let that = this;
        that.id = that.$route.params.aid;
        that.goodsname = JSON.parse(sessionStorage.getItem('goodsdata'))
        that.newtoken()
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_goodsdetails{
    height: calc(100% - 51px);
}
/* 内容查询、列表和分页 */
.d_d-content{
    height: 100%;
}
/* 查询 */
.d_d-c-query{
    display: flex;
    justify-content: space-between;
}
.d_dcq-form .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin: 0;
}
/* 表单 */
.d_d-c-list{
    display: flex;
    flex-wrap: wrap;
    height: calc(100% - 47px);
}
.d_dcl-tabel{
    width: 100%;
    color: #666666;
    border-collapse: collapse;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.d_dcl-tabel thead tr, .d_dcl-tabel tbody tr:hover{
    background-color: #F2F2F2;
}
.d_dcl-tabel tr th,.d_dcl-tabel tr td{
    height: 50px;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid #e0e0e0;
}
.d_dcl-tabel tr td img{
    max-width: 120px;
    max-height: 80px;
}
.d_rj-block{
    margin-top: auto;
}
/* 弹出层 */
.d_dc-dialog{
    display: flex;
}
</style>